<template>
  <DialogBox
    :visible="boxVisibility"
    @update:visible="boxVisibility = $event"
    resize
    max-height="800"
    :title="titleRef"
    width="40%"
    :close-on-click-modal="false"
  >
    <Form ref="ruleFormRef" label-width="120px" :model="createData" :rules="rules">
      <FormItem label="店铺名称" placeholder="请选择店铺名称" prop="store_id">
        <Select v-model="createData.store_id">
          <Option v-for="item in storeOp" :key="item.store_id" :label="item.store_name" :value="item.store_id"></Option>
        </Select>
      </FormItem>
      <FormItem label="运营人员"  placeholder="请选择运营人员" prop="operator_id">
        <Select v-model="createData.operator_id">
          <Option v-for="item in operatorOp" :key="item.user_id" :label="item.user_name" :value="item.user_id"></Option>
        </Select>
      </FormItem>
      <FormItem label="款号" prop="spu">
        <Input v-model="createData.spu" placeholder="请输入款号"></Input>
      </FormItem>
      <FormItem label="工单名称" prop="order_name">
        <Input v-model="createData.order_name" placeholder="请输入工单名称"></Input>
      </FormItem>
      <FormItem label="工单类型" prop="order_type">
        <Select v-model="createData.order_type">
          <Option v-for="item in typeOp" :key="item.value" :label="item.label" :value="item.value"></Option>
        </Select>
      </FormItem>
      <FormItem label="期望交付日期" prop="order_wish_delivery_time">
        <DatePicker v-model="createData.order_wish_delivery_time" placeholder="请选择日期" value-format="yyyy-MM-dd"></DatePicker>
        <span class="tips" v-if="titleRef === '新建工单'">提示：为避免工单挤压造成无法及时交付，请提前与对应店铺的品牌主管沟通交付周期</span>
      </FormItem>
      <FormItem label="详细介绍">
        <Input type="textarea" v-model="createData.order_detail"></Input>
      </FormItem>
      <FormItem label="上传附件" prop="order_file" validate-position="top-start">
        <FileUpload
          ref="uploadRef"
          :limit="1"
          :auto-upload="false"
          :action="'/'"
          :file-list="createData.order_file"
          @change="handleChange"
          @remove="handleRemove"
        >
          <Button type="primary">点击上传</Button>
          <span class="tips">提示：如上传大文件，可能耗时较久，请耐心等待</span>
        </FileUpload>
      </FormItem>
      <FormItem label="通知品牌部责任人" v-if="titleRef === '编辑工单'">
        <Checkbox v-model="createData.notice"></Checkbox>
      </FormItem>
    </Form>
    <template #footer>
      <Button type="primary" @click="submitClick" :disabled="disable" > 确定 </Button>
      <Button type="primary" @click="boxVisibility = false"> 取消 </Button>
    </template>
  </DialogBox>
</template>

<script setup>
import { ref, watch } from 'vue'
import { Button, DialogBox, Form, FormItem, Input, Option, Select, Checkbox, FileUpload, Modal, DatePicker } from '@opentiny/vue'
import { getRetouchOrder } from '@/request/api'
const props =  defineProps({
  basicGridRef: Object,
  storeOp: Array,
  operatorOp: Array
})
const boxVisibility = ref(false)
const titleRef = ref('新建工单')
const createData = ref({
  store_id: '',
  operator_id: '',
  spu: '',
  order_name: '',
  order_type: '',
  order_detail: '',
  order_file: [],
  notice: true,
  order_wish_delivery_time: ''
})
const disable = ref(false)
const ruleFormRef = ref()
const uploadRef = ref()
const curRow = ref()
const rules = ref(
  {
    store_id: [
      { required: true, message: '必填', trigger: 'change' },
    ],
    operator_id: [
      { required: true, message: '必填', trigger: 'change' },
    ],
    spu: [
      { required: true, message: '必填', trigger: 'change' },
    ],
    order_name: [
      { required: true, message: '必填', trigger: 'change' },
    ],
    order_type: [
      { required: true, message: '必填', trigger: 'change' },
    ],
    order_file: [
      { required: true, message: '必填', trigger: 'change' },
    ],
    order_wish_delivery_time:[
      { required: true, message: '必填', trigger: 'change' },
    ]
  }
)
const typeOp = [
  { label: '图像', value : 1 },
  { label: '视频', value : 2 },
  { label: '穿搭', value : 3 }
]
watch(boxVisibility, (val) => {
  if (!val) {
    createData.value = {
      store_id: '',
      operator_id: '',
      spu: '',
      order_name: '',
      order_type: '',
      order_detail: '',
      order_file: [],
      notice: true
    }
  }
})
const open = (title, row) => {
  boxVisibility.value = true
  createData.value.notice = true
  rules.value.order_file[0].required = true
  if (title === '编辑工单') {
    rules.value.order_file[0].required = false
    curRow.value = row
    titleRef.value = title
    createData.value.notice = false
    createData.value.store_id = row.store_id
    createData.value.operator_id = row.operator_id
    createData.value.spu = row.spu
    createData.value.order_name = row.order_name
    createData.value.order_type = row.order_type
    createData.value.order_detail = row.order_detail
    createData.value.order_wish_delivery_time = row.order_wish_delivery_time
  } else {
    titleRef.value = '新建工单'
  }
}

const getCommonParams = () => {
  const {
    store_id,
    operator_id,
    spu,
    order_name,
    order_type,
    order_detail,
    order_file,
    order_wish_delivery_time
  } = createData.value
  const formData = new FormData()
  formData.append('store_id', store_id)
  formData.append('operator_id', operator_id)
  formData.append('spu', spu)
  formData.append('order_name', order_name)
  formData.append('order_type', order_type)
  formData.append('order_detail', order_detail)
  formData.append('order_file', order_file[0]?.raw)
  formData.append('order_wish_delivery_time', order_wish_delivery_time)
  return formData
}

const add = () => {
  const params = getCommonParams()
  getRetouchOrder(params, 'post', {'content-type': 'application/x-www-form-urlencoded'}).then(res => {
    if (res?.data?.ret === 0) {
      boxVisibility.value = false
      Modal.alert({
        message: '工单创建成功，已钉钉通知品牌部抢单。10分钟内无人抢单。系统会自动分配品牌部责任人，请知悉。',
        status: 'success'
      })
      props.basicGridRef.handleFetch()
    } else {
      Modal.message({ message: res.data.msg, status: 'error' })
    }
  }).catch(() => {
    Modal.message({ message: '网络请求失败', status: 'error' })
  })
  .finally(() =>{
    disable.value = false
  })
}

const edit = () => {
  const params = getCommonParams()
  params.append('flag', 0)
  params.append('order_id', curRow.value.order_id)
  params.append('notice', Number(createData.value.notice))
  getRetouchOrder(params, 'put').then(res => {
    if (res?.data?.ret === 0) {
      boxVisibility.value = false
      Modal.message('编辑工单成功')
      props.basicGridRef.handleFetch()
    } else {
      Modal.message({ message: res.data.msg, status: 'error' })
    }
  }).catch(() => {
    Modal.message({ message: '网络请求失败', status: 'error' })
  }).finally(() =>{
    disable.value = false
  })
}
const handleRemove = () => {
  createData.value.order_file = []
}
const handleChange = (file, fileLlist) => {
  if (['zip','rar'].some(item => file.name.endsWith(item))) {
    createData.value.order_file = fileLlist
  } else {
    uploadRef.value.clearFiles()
    Modal.alert({ message: '只支持zip/rar为后缀的压缩包', title: '错误提示', status: 'error' })
  }
}

const submitClick = () => {
  ruleFormRef.value.validate((valid) => {
    if (valid) {
      disable.value = true
      if (titleRef.value === '新建工单') {
        add()
      } else {
        edit()
      }
    }
  })
}

defineExpose({
  open
})
</script>

<style scoped>
  .tips {
    margin-left: 10px;
    color: red;
  }
</style>